package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.OrderDrippingDetailResponse
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityDrippingOrderDetailBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.DrippingOrderDetailPigeonListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.DrippingViewModel
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.ext.view.isEmpty

/**
 * @Author      : hxw
 * @Date        : 2024/6/22 14:09
 * @Describe    : 交鸽订单详情
 */
class ActivityDrippingOrderDetail : BaseActivity<DrippingViewModel, ActivityDrippingOrderDetailBinding>() {

    private var orderId: String = ""
    private val mAdapter: DrippingOrderDetailPigeonListAdapter by lazy { DrippingOrderDetailPigeonListAdapter(arrayListOf()) }
    private var pigeonCatcherPhone = ""

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)

        orderId = intent.getStringExtra("id").toString()
        mViewModel.getOrderDidiDetail(orderId)

        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /**  删除/撤销订单 */
        mViewModel.deleteDrippingOrderResult.observe(this) {
            mViewModel.getOrderDidiDetail(orderId)
        }
        /** 获取订单详情 */
        mViewModel.drippingOrderDetailResult.observe(this) {
            if (it != null) {
                refreshUi(it)
                if (it.list != null && it.list.pigeons.isNotEmpty()) {
                    mAdapter.setList(it.list.pigeons)
                    mAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun refreshUi(it: OrderDrippingDetailResponse) {
        mDatabind.data = it
        pigeonCatcherPhone = it.transporterMobile
        val driverName = it.transporterName
        if (pigeonCatcherPhone.isNotEmpty() && pigeonCatcherPhone.length >= 11) {
            val result1 = pigeonCatcherPhone.substring(0, 3)
            val result2 = pigeonCatcherPhone.substring(7, pigeonCatcherPhone.length)
            mDatabind.tvUserOrderDetailPhone.text = "电话: $result1****$result2"
        } else {
            mDatabind.tvUserOrderDetailPhone.text = "电话: 暂无"
        }
        if (driverName.isNotEmpty()) {
            val result = driverName.substring(0)
            mDatabind.tvUserOrderDetailDriverName.text = "接鸽员: " + result + "师傅"
        } else {
            mDatabind.tvUserOrderDetailDriverName.text = "接鸽员: 暂无"
        }
        mDatabind.tvUserOrderDetailPigeonCount.text = "交鸽羽数: ${it.list?.pigeons?.size}羽"
        val title = when (it.status) {//1创建2发布3已接单4已接鸽5已完成
            1, 2 -> "待接单"
            3 -> "已被接单"
            4 -> "已接鸽"
            else -> "已完成"
        }
        mDatabind.includeBar.tvTitle.text = title
        mDatabind.btnChargeBackOrder.isVisible = it.status == 2 || it.status == 3
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.tvCallPhone, mDatabind.btnChargeBackOrder) {
            when (it) {
                mDatabind.btnChargeBackOrder -> {
                    showDialog()
                }

                mDatabind.tvCallPhone -> {
                    showDeleteDialog()
                }

                mDatabind.includeBar.ivBack -> {
                    finish()
                }
            }
        }
    }

    private fun showDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setContent("当天内最多可操作3次撤单，超出则不可再次进行发单，请谨慎操作！")
        dialog.setLeftBtnContent("再想想")
        dialog.setRightBtnContent("确认撤单")
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            mViewModel.deleteOrderDidi(orderId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showDeleteDialog() {
        if (pigeonCatcherPhone.isEmpty()) {
            RxToast.showToast("电话为空")
            return
        }
        val dialog = RxDialogDefault(this)
        dialog.setTitle("确定向以下手机号拨打电话？")
        dialog.setContent(pigeonCatcherPhone)
        dialog.setSureListener {
            requestPermission()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun requestPermission() {
        XXPermissions.with(this)
            .permission(Permission.CALL_PHONE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_CALL)
                    val data = Uri.parse("tel:$pigeonCatcherPhone")
                    intent.setData(data)
                    startActivity(intent)
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }
}